package config

import (
	"fmt"

	"github.com/spf13/viper"
)

// Config 应用配置结构
type Config struct {
	App      AppConfig      `mapstructure:"app"`
	Database DatabaseConfig `mapstructure:"database"`
	Server   ServerConfig   `mapstructure:"server"`
	Scraper  ScraperConfig  `mapstructure:"scraper"`
    Logger   LoggerConfig   `mapstructure:"logger"`
}

// AppConfig 应用配置
type AppConfig struct {
	Name        string `mapstructure:"name"`
	Version     string `mapstructure:"version"`
	Environment string `mapstructure:"environment"`
	Mode        string `mapstructure:"mode"`
}

// ConnectionPoolConfig 连接池配置
type ConnectionPoolConfig struct {
	MaxOpenConnections     int `mapstructure:"max_open_connections"`
	MaxIdleConnections     int `mapstructure:"max_idle_connections"`
	ConnectionMaxLifetime  int `mapstructure:"connection_max_lifetime"`
}

// TimeoutConfig 超时配置
type TimeoutConfig struct {
	Connect int `mapstructure:"connect"`
	Read    int `mapstructure:"read"`
	Write   int `mapstructure:"write"`
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	Username       string              `mapstructure:"username"`
	Password       string              `mapstructure:"password"`
	Host           string              `mapstructure:"host"`
	Port           int                 `mapstructure:"port"`
	Database       string              `mapstructure:"database"`
	TableName      string              `mapstructure:"tablename"`
	ConnectionPool ConnectionPoolConfig `mapstructure:"connection_pool"`
	Timeout        TimeoutConfig       `mapstructure:"timeout"`
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Host         string `mapstructure:"host"`
	Port         int    `mapstructure:"port"`
	ReadTimeout  int    `mapstructure:"read_timeout"`
	WriteTimeout int    `mapstructure:"write_timeout"`
}

// ScraperConfig 抓取配置
type ScraperConfig struct {
	BaseURL              string   `mapstructure:"base_url"`
	TargetURLs           []string `mapstructure:"target_urls"`
	MaxConcurrency       int      `mapstructure:"max_concurrency"`
	DelayBetweenRequests int      `mapstructure:"delay_between_requests"`
	RetryAttempts        int      `mapstructure:"retry_attempts"`
	UserAgents           []string `mapstructure:"user_agents"`
}

// LoggerConfig 日志配置
type LoggerConfig struct {
	Level  string `mapstructure:"level"`
	Format string `mapstructure:"format"`
    Output LoggerOutputConfig `mapstructure:"output"`
}

// LoggerOutputConfig 日志输出配置
type LoggerOutputConfig struct {
    Console ConsoleOutputConfig `mapstructure:"console"`
    File    FileOutputConfig    `mapstructure:"file"`
}

type ConsoleOutputConfig struct {
    Enabled bool   `mapstructure:"enabled"`
    Format  string `mapstructure:"format"`
}

type FileOutputConfig struct {
    Enabled    bool   `mapstructure:"enabled"`
    Path       string `mapstructure:"path"`
    Filename   string `mapstructure:"filename"`
    MaxSize    int    `mapstructure:"max_size"`
    MaxBackups int    `mapstructure:"max_backups"`
    MaxAge     int    `mapstructure:"max_age"`
    Compress   bool   `mapstructure:"compress"`
}

// LoadConfig 加载配置文件
func LoadConfig(configPath string) (*Config, error) {
	viper.SetConfigFile(configPath)
	viper.SetConfigType("json")

	if err := viper.ReadInConfig(); err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return &config, nil
}

// GetDSN 获取数据库连接字符串
func (c *DatabaseConfig) GetDSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		c.Username, c.Password, c.Host, c.Port, c.Database)
}
